package com.ha8.netease.controllers
{
	import com.ha8.netease.App;
	import com.ha8.netease.views.components.UpdateWindow;
	import com.ha8.netease.views.events.CusEvent;
	import com.ha8.netease.views.utils.ToolTipUtil;
	import com.rogo.events.UpdateEvent;
	import com.rogo.mvc.interfaces.INotification;
	import com.rogo.mvc.sub.command.Command;
	import com.rogo.utils.UpdateUtil;
	
	import flash.events.Event;
	
	public class UpdateAppCommand extends Command
	{
		public function UpdateAppCommand()
		{
			super();
			
			updater = new UpdateUtil(App.UPDATE_URL);
			updater.addEventListener(UpdateEvent.CHECK_RESULT, updater_checkResultHandler);
			updater.addEventListener(UpdateEvent.ERROR, updater_errorHandler);
		}
		
		private var updater:UpdateUtil;
		private var tipEnable:Boolean = false;
		
		override public function execute(notification:INotification):void
		{
			tipEnable = notification.param as Boolean;
			updater.checkVersion();
		}
		
		private function updater_checkResultHandler(e:UpdateEvent):void
		{
			if (e.available)
			{
				// new version found
				if (App.getInstance().updateWindow)
				{
					App.getInstance().updateWindow.activate();
				}
				else
				{
					App.getInstance().updateWindow = new UpdateWindow();
					App.getInstance().updateWindow.addEventListener(Event.CLOSE, updateWindow_closeHandler);
					App.getInstance().updateWindow.addEventListener(CusEvent.YES, yesHandler);
					App.getInstance().updateWindow.addEventListener(CusEvent.CANCEL, cancelHandler);
					App.getInstance().updateWindow.open();
				}
				App.getInstance().updateWindow.htmlText = '更新版本: ' + updater.remoteVersionLabel + '\r' +
					'当前版本: ' + updater.nowVersionLabel + '\r' +
					'更新内容:\r' + updater.description;
			}
			else
				tipMsg('没有可用更新');
		}
		
		private function updater_errorHandler(e:UpdateEvent):void
		{
			tipMsg('更新失败');
		}
		
		private function tipMsg(msg:String):void
		{
			if (tipEnable)
				ToolTipUtil.alert(msg);
		}
		
		private function updateWindow_closeHandler(e:Event):void
		{
			App.getInstance().updateWindow = null;
		}
		
		private function cancelHandler(e:CusEvent):void
		{
			// do nothing
		}
		
		private function yesHandler(e:CusEvent):void
		{
			tipEnable = true;
			tipMsg('正在更新');
			updater.update();
		}
		
	}
}